package com.hn658.base.message.notisender.sender.comet;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.servlet.AsyncContext;

import com.hn658.framework.logging.Logger;
import com.hn658.framework.logging.LoggerFactory;
import com.hn658.framework.logging.enums.LogCategory;


/**
 * 服务器端推送长链接缓存
 *
 * @author ztjie
 */
public class AsyncContextCache {

	/**
     * 日志记录器
     */
    private static final Logger logger = LoggerFactory.getLogger(AsyncContextCache.class);
    
    /**
     * 长链接保存队列
     */
    private static Map<String, AsyncContext> ASYNC_CONTEXT_QUEUE = new ConcurrentHashMap<String, AsyncContext>();
    

    /**
     * 
     * <p>长链接缓存中获得，长链接对象</p> 
     * @author ztjie
     * @date 2014-11-26 下午3:58:06
     * @param appUid
     * @return
     * @see
     */
    public static AsyncContext get(String appUid){
    	AsyncContext asyncContext = ASYNC_CONTEXT_QUEUE.get(appUid);
    	if(asyncContext!=null){
    		return asyncContext;
    	}else{
    		logger.debug(LogCategory.SYSTEM,
    				"当前ASYNC_CONTEXT_QUEUE中获取不到编号为：{}的长连接", appUid);
    		return null;
    	}
    }
    
    /**
     * 
     * <p>删除长链接对象</p> 
     * @author ztjie
     * @date 2014-11-26 下午3:58:43
     * @param appUid
     * @see
     */
    public static void remove(String appUid){
    	logger.debug(LogCategory.SYSTEM,
				"当前ASYNC_CONTEXT_QUEUE中删除长链接编号为：{}的长连接", appUid);
    	ASYNC_CONTEXT_QUEUE.remove(appUid);
    }
    
    /**
     * 
     * <p>增加长链接对象</p> 
     * @author ztjie
     * @date 2014-11-26 下午3:59:02
     * @param appId
     * @param uid
     * @param context
     * @param onlineManager
     * @see
     */
    public static void add(String appId,String uid, AsyncContext asyncContext, IIsOnlineManager onlineManager){
    	String appUid=uid+"_"+appId;
    	logger.debug(LogCategory.SYSTEM,
				"当前ASYNC_CONTEXT_QUEUE中增加长链接编号为：{}的长连接,长连接对象: {}", appUid, asyncContext);
        // 设置30秒超时
        asyncContext.setTimeout(30 * 1000);
        CometAsyncListener listener = new CometAsyncListener(appId,uid,onlineManager);
        asyncContext.addListener(listener);
    	ASYNC_CONTEXT_QUEUE.put(appUid, asyncContext);
    }
}
